package com.example.vue3;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.example.vue3.model.ResultCode;
import com.example.vue3.model.ResultData;
import org.apache.tomcat.util.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 系统全局异常处理
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2021/12/28 15:03
 */
@RestControllerAdvice
public class CommonExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(CommonExceptionHandler.class);

    /**
     * 对没有具体捕获的异常统一捕获处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler()
    @ResponseStatus(HttpStatus.OK)
    public ResultData<Object> handleException(Exception ex) {
        log.error(ex.getMessage(), ex);
        // 堆栈转为完整字符串(默认3k个字符长度)
        String stacktraceToString = ExceptionUtil.stacktraceToString(ex, 30000);
        return new ResultData<>(ResultCode.FAIL, null, stacktraceToString);
    }
}